<template>
  <el-card class="container">
    <searchComponent v-model:search-list="searchList" :button-list="buttonList" @doSearch="handleSearch"/>
    <tableComponent class="mg-t-20" :table-data="tableData" :table-head="tableHead" row-key="id"
                    @selection-change="handleSelectionChange" :page-info="pageInfo" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
      <template #operate="scope">
        <div class="flex">
          <el-button type="text" size="small" @click="doExport(scope.row)">下载回单</el-button>
        </div>
      </template>
      <template #billStatus="scope">
        <div>
          {{ (scope.row.billStatus === null ? '未申请' : scope.row.billStatus === 1 ? '申请中' : scope.row.billStatus === 2 ? '已完成' : '未申请') }}
        </div>
      </template>
    </tableComponent>
  </el-card>
  <dialogExportDetails v-model:show="showDetails" :default-status="1" :filter-data="searchList"/>

</template>

<script lang="ts">
import { defineComponent } from 'vue'
import {ElMessageBox, ElMessage, ElLoading} from 'element-plus'

import searchComponent from '@/components/search-component/index.vue'
import tableComponent from '@/components/table-component/index.vue'
import dialogExportDetails from './components/dialog-export-details.vue'

import { listReceived, exportRecord } from '@/api/salary'
import dayjs from 'dayjs'
import {batchApplyEle, batchDownloadEle, downloadPayrollRecordEle, payrollRecordEle} from "@/api/operation";
import axios from "axios";
import {closewin} from "@/utils/util";
const firstDay = dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD')
const lastDay = dayjs().endOf('month').format('YYYY-MM-DD')

export default defineComponent({
  name: 'SalaryPaid',
  components: {
    searchComponent,
    tableComponent,
    dialogExportDetails
  },
  data() {
    return {
      searchList: {
        searchText: {
          name: '搜索',
          prop: 'searchText',
          type: 'input',
          placeholder: '请输入姓名/手机号/身份证',
          value: '',
          defaultValue: ''
        },
        serveCompanyName: {
          name: '所属企业',
          prop: 'serveCompanyName',
          type: 'input',
          placeholder: '请输入派遣单位名称',
          value: '',
          defaultValue: ''
        },
        projectName: {
          name: '所属项目',
          prop: 'projectName',
          type: 'input',
          placeholder: '请输入项目名称',
          value: '',
          defaultValue: ''
        },
        payTime: {
          name: '发薪时间',
          prop: 'PayTime',
          type: 'dateRange',
          startPlaceholder: '开始时间',
          endPlaceholder: '结束时间',
          value: [firstDay, lastDay],
          defaultValue: [firstDay, lastDay],
          handleChange: (item: any) => {
            if (item.value?.length) {
              const startTime = new Date(item.value[0]).getTime()
              const endTime = new Date(item.value[1]).getTime()
              const startMonth = dayjs(startTime).month()
              const endMonth = dayjs(endTime).month()
              const limitDay = (startMonth + 1 === 7 && endMonth + 1  === 8 ) ? 61 : 60
              if (endTime - startTime > limitDay * 24 * 60 * 60 * 1000) {
                ElMessage({
                  message: '最多只能选择61天',
                  type: 'warning'
                })
                item.value = []
                return
              }
            }
          }
        },
        getSalaryTime: {
          name: '领薪时间',
          prop: 'GetSalaryTime',
          type: 'dateRange',
          startPlaceholder: '开始时间',
          endPlaceholder: '结束时间',
          value: [],
          handleChange: (item: any) => {
            if (item.value?.length) {
              const startTime = new Date(item.value[0]).getTime()
              const endTime = new Date(item.value[1]).getTime()
              const startMonth = dayjs(startTime).month()
              const endMonth = dayjs(endTime).month()
              const limitDay = (startMonth + 1 === 7 && endMonth + 1  === 8 ) ? 61 : 60
              if (endTime - startTime > limitDay * 24 * 60 * 60 * 1000) {
                ElMessage({
                  message: '最多只能选择61天',
                  type: 'warning'
                })
                item.value = []
                return
              }
            }
          }
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
      } as any,
      buttonList: [
        {
          name: '一键申请微信回单',
          icon: 'export',
          plain: true,
          fn: () => {
            this.applyReceipt((this as any).selects)
          }
        },
        {
          name: '一键下载微信回单',
          icon: 'export',
          type: 'success',
          plain: true,
          fn: async () => {
            this.downloadPayrollRecordEle((this as any).selects)
          }
        },
        {
          name: '导出名单',
          buttonType: 'export',
          fn: () => {
            if((this as any).selects?.length) {
              this.handleExport((this as any).selects)
            } else {
              ;(this as any).showDetails = true
            }
          }
        }
      ] as any,
      tableHead: [
        {
          prop: 'index'
        },
        {
          prop: 'cardholderName',
          label: '姓名'
        },
        {
          prop: 'idCardNo',
          label: '身份证号',
          width: 170
        },
        {
          prop: 'phone',
          label: '手机号',
          width: 120
        },
        {
          prop: 'projectName',
          label: '所属项目',
          width: 150
        },
        {
          prop: 'serveCompanyName',
          label: '所属企业',
          width: 200
        },
        {
          prop: 'detailRemarks',
          label: '发薪备注',
          width: 150
        },
        {
          prop: 'paymentAmount',
          label: '已领金额',
          suffix: '元'
        },
        {
          prop: 'payTime',
          label: '发薪时间',
          width: 160
        },
        {
          prop: 'getSalaryTime',
          label: '领薪时间',
          width: 160
        },
        {
          prop: 'billStatus',
          label: '回单状态'
        },
        {
          prop: 'operate',
          label: '操作',
          width: 100,
          fixed: 'right'
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
      ] as any,
      tableData: [

        // eslint-disable-next-line @typescript-eslint/no-explicit-any
      ] as any,
      pageInfo: {
        pageNum: 1,
        pageSize: 10,
        total: 0
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
      } as any,
      selects: [],
      showDetails: false
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    handleSelectionChange(row: any) {
      this.selects = row.map((item: any) => item.id)
    },
    getData() {
      const query = this.createQuery()
      listReceived(query).then((res: any) => {
        this.tableData = res.list
        this.pageInfo.total = res.total
        this.$emit('total', res.total)
      })
    },
    createQuery(hasPage = true) {
      const query = {} as any
      if (hasPage) {
        query.pageNum = this.pageInfo.pageNum
        query.pageSize = this.pageInfo.pageSize
      }
      for (const key in this.searchList) {
        if (this.searchList[key].type === 'dateRange') {
          query[`begin${this.searchList[key].prop}`] = this.searchList[key].value?.length ? this.searchList[key].value[0] : ''
          query[`end${this.searchList[key].prop}`] = this.searchList[key].value?.length ? this.searchList[key].value[1] : ''
        } else {
          query[(this.searchList[key]).prop] = this.searchList[key].value
        }
      }
      return query
    },
    handleSearch() {
      this.pageInfo.pageNum = 1
      this.getData()
    },
    handleSizeChange(ev: number) {
      this.pageInfo.pageSize = ev
      this.getData()
    },
    handleCurrentChange(ev: number) {
      this.pageInfo.pageNum = ev
      this.getData()
    },
    handleExport(ids: any) {
      const query = this.createQuery(false)
      query.ids = ids.join(',')
      query.status = 1
      exportRecord(query).then(res => {
        window.location.href =
          process.env.VUE_APP_BASE_URL +
          '/common/download?delete=true&fileName=' +
          res
        this.$message.success('导出成功！')
      })
    },
    async doExport(row: any) {
      this.downloadPayrollRecordEle([row.id])
    },
    // 一键申请回单
    applyReceipt() {
      payrollRecordEle({
        ids: this.selects.join(','),
        beginPayTime: this.searchList.payTime?.value?.length ? this.searchList.payTime.value[0] : '',
        endPayTime: this.searchList.payTime?.value?.length ? this.searchList.payTime.value[1] : '',
        beginGetSalaryTime: this.searchList.getSalaryTime?.value?.length ? this.searchList.getSalaryTime.value[0] : '',
        endGetSalaryTime: this.searchList.getSalaryTime?.value?.length ? this.searchList.getSalaryTime.value[1] : '',
      }).then(() => {
        ElMessage.success('申请成功')
        this.getData()
      })
    },
    // 下载申请回单 downloadPayrollRecordEle
    async downloadPayrollRecordEle(ids: any) {
      this.downloadReceiptOld(ids)
    },
    async downloadReceiptOld(ids: any) {
      const result = await downloadPayrollRecordEle({
        ids: ids.join(',')
      })
      this.windowOpen()

      document.title = '正在下载中...'
      const loading = await ElLoading.service({
        fullscreen: true,
        text: '回单正在下载中，您可以在新界面继续操作'
      })
      const files = await axios({
        url:
          'https://1403244436326619.cn-shanghai.fc.aliyuncs.com/2016-08-15/proxy/zip-service/zip-oss/',
        method: 'post',
        data: result
      })
      window.location.href = files.data
      await this.$message.success('导出成功！')
      await loading.close()
      closewin()
    },
    windowOpen() {
      window.open(
        window.location.pathname +
        '?tip#/pay'
      )
      const channel = new BroadcastChannel('new_tab_payroll')
      const timer = setInterval(() => {
        channel.postMessage(JSON.stringify({
          // payDateSolt: this.payDateSolt,
          // paidTime: this.paidTime,
          // searchValue: this.searchValue,
          // pageSize: this.pageSize,
          // pageNum: this.pageNum,
          // enterpriseName: this.enterpriseName,
          // payType: this.payType,
          // searchText: this.searchText
          ...this.searchList
        }))
        console.log('postMessage')
      }, 50)
      channel.onmessage = e => {
        if (e.data === 'payroll_close') {
          clearInterval(timer)
          channel.close()
        }
      }
    }
  }
})
</script>

<style scoped lang="stylus">

</style>
